# 导入所需要的工具包
import numpy as np
import matplotlib.pyplot as plt

# 准备数据集，x_data存放每条数据的属性值，y_data存放每条数据的标签值
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

# 计算正向传播结果 y_pred = x * w
def forward(x):
    return x * w

# 计算损失值 loss = (y_pred - y)^2
def loss(x, y):
    y_pred = forward(x)
    return (y_pred - y) * (y_pred - y)

# 将权重系数和损失值分别存放到w_list和mse_list中为画图做准备
w_list = []
mse_list = []

# 尝试计算w取不同值时的损失值
for w in np.arange(0.0, 4.1, 0.1):
    print('w=', w)
    l_sum = 0
    for x_val, y_val in zip(x_data, y_data):
        y_pred_val = forward(x_val)
        loss_val = loss(x_val, y_val)
        l_sum += loss_val
        print('\t', x_val, y_val, y_pred_val, loss_val)
        print('MSE=', l_sum / 3)
    w_list.append(w)
    mse_list.append(l_sum / 3)

plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('Weight')
plt.show()